
skytruth.startZoom = 13;
skytruth.startLat = 35.56798;
skytruth.startLng = -120.541992;
skytruth.markersWorklet = document.location.protocol + "//" +
        document.location.hostname +
        "/locations/";
skytruth.detailWorklet = document.location.protocol + "//" +
        document.location.hostname +
        "/map/infowindow/location/";


skytruth.ProtoMap = function(element, center, zoom, q, radius){
    var mEl = typeof element == "string" ? document.getElementById(element) : element;
    
    this.searchradius = radius;
    this.searchcenter = center;
    this.addMode = false;
    skytruth.mapRef = this;
    
    skytruth.sbEl = document.getElementById("sidebar");
    skytruth.resEl = document.getElementById("resultscontainer");
    
    this.stMap = new skytruth.Map(mEl, center, zoom);
    this.map = this.stMap.getGMap();
    //this.map.setMapType(G_SATELLITE_MAP);
    this.map.setMapType(G_NORMAL_MAP);
    this.map.addControl(new GLargeMapControl());
    this.map.addControl(new GMapTypeControl());
    this.markers = [];
    this.clusters = new Object();
    var blueDotIcon = this.getCustomIcon("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
    //this.clusterIcon = this.getCustomIcon("http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png");
    this.clusterIcon = this.getCustomIcon("/resources/icons/cluster-orange-35.png", "/resources/icons/cluster-shadow.png");
    this.cluster0_75Icon = this.getCustomIcon("/resources/icons/cluster-orange-35.png", "/resources/icons/cluster-shadow.png", .75, null, .75);
    this.cluster1_25Icon = this.getCustomIcon("/resources/icons/cluster-orange-35.png", "/resources/icons/cluster-shadow.png", 1.25, null, 1.25);
    this.cluster1_75Icon = this.getCustomIcon("/resources/icons/cluster-orange-35.png", "/resources/icons/cluster-shadow.png", 1.75, null, 1.75);
    var markerOptions = {
        draggable: false,
        icon: blueDotIcon,
        zIndexProcess: setZIndex
    };
    this.centerMarker = new GMarker(center, markerOptions);
    this.centerMarker.markerType = "center";
    this.map.addOverlay(this.centerMarker);
    this.centerMarker.openInfoWindowHtml("<h2>" + q + "</h2>");
    var parent = this;
    var moveEventHandler = function(){
        parent.getMarkers();
    }
    GEvent.addListener(this.map, "moveend", moveEventHandler);
    this.getMarkers();
}

skytruth.ProtoMap.prototype.getMarkers = function(){
    var bounds = this.map.getBounds();
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    /*var featureWorklet = skytruth.markersWorklet + 
     "?sc=" + this.searchcenter.lat() + ',' + this.searchcenter.lng() +
     "&sr=" + this.searchradius;*/
    var featureWorklet = skytruth.markersWorklet +
    "?z=" +
    this.map.getZoom() +
    "&b=" +
    sw.toUrlValue() +
    "," +
    ne.toUrlValue();
    if (layers && layers != "") {
        featureWorklet += "&layers=" + layers;
    }
    var featureRequest = GXmlHttp.create();
    var parent = this;
    featureRequest.onreadystatechange = function(){
        if (featureRequest.readyState == 4) {
            parent.showFeatures(featureRequest.responseText);
        }
    }
    featureRequest.open("GET", featureWorklet, true);
    featureRequest.send("");
}

skytruth.ProtoMap.prototype.showFeatures = function(json){
    var toDelete = skytruth.shallowClone(this.markers);
    var features = eval(json);
    var id;
    //this.markers = [];
    for (var i = 0; i < features.length; i++) {
        id = features[i].pk;
        // Add the marker
        var marker;
        var point_count = features[i].fields.point_count;
        if (toDelete[id] != null) {
            // Feature already exists so don't delete it and don't re-add it
            delete toDelete[id];
            continue;
        }
        if (point_count == 1) {
            marker = this.addPoint(features[i]);
        //            this.markers[id] = marker;
        }
        else if (point_count > 1) {
                marker = this.addCluster(features[i]);
            //                this.clusters[id] = marker;
        }
        this.map.addOverlay(marker);
        this.markers[id] = marker;
    }
    
    for (var id in toDelete) {
        //      remove overlay from map
        this.map.removeOverlay(toDelete[id]);
        //      remove from active_features
        delete this.markers[id];
    }
    /*for (cluster in this.clusters) {
        this.map.removeOverlay(cluster);
        delete this.clusters[cluster];
    }*/
}

skytruth.ProtoMap.prototype.addPoint = function(feature){
    var pointWkt = feature.fields.coordinates;
    var coords = this.parseWkt(feature.fields.coordinates);
    var name = feature.fields.name;
    
    var markerOptions = {
        draggable: false,
        zIndexProcess: setZIndex,
        title: name
    };
    var marker = new GMarker(new GLatLng(coords[1], coords[0]), markerOptions);
    marker.pid = feature.pk;
    var parent = this;
    GEvent.addListener(marker, "click", function(){
        parent.handleMarkerClick(marker);
    });
    return marker;
}

skytruth.ProtoMap.prototype.addCluster = function(cluster){
    var clusterWkt = cluster.fields.coordinates;
    var coords = this.parseWkt(clusterWkt);
    var icon;
    var pointCount = cluster.fields.point_count;
    if (pointCount < 3) {
        icon = this.cluster0_75Icon;
    }
    else if (pointCount > 8) {
        icon = this.cluster1_25Icon;
    }
    else if (pointCount > 15) {
        icon = this.cluster1_75Icon;
    }
    else {
        icon = this.clusterIcon;
    }
    var markerOptions = {
        draggable: false,
        zIndexProcess: setZIndex,
        icon: icon,
        title: cluster.fields.point_count + " Sites"
    };
    var marker = new GMarker(new GLatLng(coords[1], coords[0]), markerOptions);
    marker.pid = cluster.pk;
    marker.pointCount = cluster.fields.point_count;
    return marker;
}

skytruth.ProtoMap.prototype.getCustomIcon = function(iconImage, shadowImage, iconSizeMult, iconAnchor, shadowSizeMult, infoWindowAnchor, infoShadowAnchor) {
    if (!shadowImage) {
        shadowImage = "http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png";
    }
    var customIcon = new GIcon();
    if (iconSizeMult) {
        customIcon.iconSize = new GSize(32*iconSizeMult, 32*iconSizeMult);
    }
    else {
        customIcon.iconSize = new GSize(32, 32);
    }
    customIcon.iconAnchor = new GPoint(16, 32);
    if (shadowSizeMult) {
        customIcon.shadowSize = new GSize(59*iconSizeMult, 32*iconSizeMult);
    }
    else {
        customIcon.shadowSize = new GSize(59, 32);
    }
    customIcon.shadow = "http://maps.google.com/mapfiles/ms/micons/msmarker.shadow.png";
    customIcon.infoWindowAnchor = new GPoint(9, 2);
    customIcon.infoShadowAnchor = new GPoint(18, 25);
    var tmpIcon = new GIcon(customIcon);
    tmpIcon.image = iconImage;
    return tmpIcon;
}

skytruth.ProtoMap.prototype.handleMarkerClick = function(m){
    this.centerMarker.closeInfoWindow();
    //skytruth.sbEl.src = "/map/sidebar/location/" + m.pid;

    var detailWorklet = skytruth.detailWorklet + m.pid + "/";
    var detailRequest = GXmlHttp.create();
    var parent = this;
    detailRequest.onreadystatechange = function(){
        if (detailRequest.readyState == 4) {
            parent.showInfoWindow(m, detailRequest.responseText);
        }
    }
    detailRequest.open("GET", detailWorklet, true);
    detailRequest.send("");

    m.openInfoWindowHtml("<div style='width: 500px; text-align: center;'><img src='/resources/images/loading-large.gif' /></div>");
//    m.openInfoWindowHtml(m.getTitle());
//    showSidebar();
}

skytruth.ProtoMap.prototype.showInfoWindow = function(m, html){
    m.openInfoWindowHtml(html);
}

skytruth.ProtoMap.prototype.toggleAddMode = function(keepMarker){
    if (!this.addMode) {
        var greenIcon = this.getCustomIcon("http://www.google.com/intl/en_us/mapfiles/ms/micons/green.png");
        var markerOptions = {
            draggable: true,
            icon: greenIcon
        };
        var c = this.map.getCenter();
        this.newLocMarker = new GMarker(c, markerOptions);
        
        var parent = this;
        this.addClickHandler = GEvent.addListener(this.newLocMarker, "dragend", function(){
            parent.handleMarkerPlaced();
        });
        
        this.map.addOverlay(this.newLocMarker);
        document.getElementById("addnewlink").innerHTML = "Stop adding markers";
        
        showSidebar("addmarker.html?lat=" + c.lat() + "&lng=" + c.lng());
        
        this.addMode = true;
        
    }
    else {
        GEvent.removeListener(this.addClickHandler);
        document.getElementById("addnewlink").innerHTML = "<img style='vertical-align: middle; padding: 3px;' src='resources/images/add-sm.png' />Add a new marker";
        if (!keepMarker) {
            this.map.removeOverlay(this.newLocMarker);
        }
        showSearchResults();
        this.addMode = false;
    }
    
}

skytruth.ProtoMap.prototype.handleMarkerPlaced = function(m){
    var point = this.newLocMarker.getLatLng();
    top.sidebar.updateCoords(point.lat(), point.lng());
    top.sidebar.mapRef = this;
}

skytruth.ProtoMap.prototype.markerAdded = function(pid, name){
    var markerOptions = {
        draggable: false,
        title: name
    };
    var marker = new GMarker(this.newLocMarker.getLatLng(), markerOptions);
    marker.pid = pid
    var parent = this;
    GEvent.addListener(marker, "click", function(){
        parent.handleMarkerClick(marker);
    });
    this.map.removeOverlay(this.newLocMarker);
    this.map.addOverlay(marker);
    
    // Go ahead and fire the handleMarkerClick event.
    this.handleMarkerClick(marker);
    
    if (this.addMode) {
        this.toggleAddMode(true);
    }
}

skytruth.ProtoMap.prototype.loadGroundOverlay = function(){
    var sw = new GLatLng(59.77215098947377, -155.6135870455874);
    var ne = new GLatLng(59.98569347229613, -155.0810544489622);
    var overlayBounds = new GLatLngBounds(sw, ne);
    this.groundOverlay = new GGroundOverlay("http://dev.skytruth.org/kml/skytruth_pebble_mine_plan_apr07_utm4wgs84_scaled.png", overlayBounds);
    
}

skytruth.ProtoMap.prototype.toggleOverlay = function(){
    if (this.overlayLoaded) {
        this.removeGroundOverlay();
    }
    else {
        if (!this.groundOverlay) {
            this.loadGroundOverlay();
        }
        this.addGroundOverlay();
    }
}

skytruth.ProtoMap.prototype.removeGroundOverlay = function(){
    this.map.removeOverlay(this.groundOverlay);
    this.overlayLoaded = false;
}

skytruth.ProtoMap.prototype.addGroundOverlay = function(){
    this.map.addOverlay(this.groundOverlay);
    this.overlayLoaded = true;
}

skytruth.ProtoMap.prototype.highlightMarker = function(pid){
    console.debug(pid);
    this.handleMarkerClick(this.markers[pid]);
}

skytruth.ProtoMap.prototype.parseWkt = function(wkt){
    var coords;
    if (wkt.substr(0, 5) == 'POINT') {
        var wktnums = wkt.substring(wkt.indexOf("(") + 1, wkt.indexOf(")"));
        coords = wktnums.split(" ");
    }
    return coords;
}

function showSidebar(url){
    if (url) {
        skytruth.sbEl.src = url;
    }
    skytruth.sbEl.style.display = "block";
    skytruth.resEl.style.display = "none";
}

function showSearchResults(){
    skytruth.sbEl.style.display = "none";
    skytruth.resEl.style.display = "block";
}

function setZIndex(marker, up){
    if (marker.markerType == "center") {
        return -2;
    }
    else {
        return -1;
    }
}

function maxHeight(){
    var h = 0;
    if (window.document.innerHeight > h) 
        h = window.document.innerHeight;
    if (window.document.documentElement.clientHeight > h) 
        h = window.document.documentElement.clientHeight;
    if (window.document.body.clientHeight > h) 
        h = window.document.body.clientHeight;
    return h;
}

function maxWidth(){
    var w = 0;
    if (window.document.innerWidth > w) 
        w = window.document.innerWidth;
    if (window.document.documentElement.clientWidth > w) 
        w = window.document.documentElement.clientWidth;
    if (window.document.body.clientWidth > w) 
        w = window.document.body.clientWidth;
    return w;
}

function resizeMap(){
    mapEl.style.width = (maxWidth() - 350) + "px";
}
